package com.szlanyou.thirdsdk.retrofit.client;

import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * @author : 陈章 on 2016/6/21 0021.
 * des:
 * 底层Retrofit层
 */
public class RetrofitClient {
    private String BASE_URL = "http://127.0.0.1/";
    private Retrofit retrofitInstance = null;
    private Retrofit.Builder retrofitBuilder;
    private HttpClient httpClient;

    protected RetrofitClient(HttpClient httpClient) {
        this.httpClient = httpClient;
    }

    private Retrofit getDefaultRetrofitClient() {
        if (retrofitBuilder == null) {
            retrofitBuilder = new Retrofit.Builder().baseUrl(BASE_URL)
                    .client(RetrofitUtil.generateOkHttpClient(httpClient))
                    //添加gson转换器
                    .addConverterFactory(GsonConverterFactory.create())
                    //添加 RxJava 适配器
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create());
        }
        retrofitInstance = retrofitBuilder.build();
        return retrofitInstance;
    }

    /**
     * 得到RxJava的请求接口服务
     *
     * @param serviceClass
     * @param <T>
     * @return
     */
    public <T> T getService(Class<T> serviceClass) {
        return getDefaultRetrofitClient().create(serviceClass);
    }

    public void setBaseUrl(String baseUrl) {
        BASE_URL = baseUrl;
        onRetrofitSetChanged();
    }

    private void onRetrofitSetChanged() {
        if (retrofitBuilder == null) {
            return;
        }
        retrofitBuilder.baseUrl(BASE_URL);
        retrofitBuilder.client(RetrofitUtil.generateOkHttpClient(httpClient));
    }

    public String getBaseUrl() {
        return BASE_URL;
    }
}
